package web.servlet;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import web.servlet.dto.DtoFactory;
import data.model.ChatMessage;

public class ChatServlet extends AbstractJsonCapableServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final String groupId = request.getParameter("groupId");
        final long counter = Long.valueOf(request.getParameter("messageCounter"));

        jsonHandler.writeAsJson(DtoFactory.createMessageList(dataLayer.findMessageAfterCounter(groupId, counter), dataLayer.findCurrentMessageCounter(groupId)), response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final String groupId = request.getParameter("groupId");
        final String owner = request.getParameter("email");
        final String content = request.getParameter("text");

        final ChatMessage message = new ChatMessage();
        message.setGroupId(groupId);
        message.setOwner(owner);
        message.setText(content);
        message.setDate(new Date());
        message.setMessageCounter(dataLayer.findCurrentMessageCounter(groupId) + 1);
        dataLayer.addObject(message);

        final long counter = Long.valueOf(request.getParameter("messageCounter"));
        jsonHandler.writeAsJson(DtoFactory.createMessageList(dataLayer.findMessageAfterCounter(groupId, counter), dataLayer.findCurrentMessageCounter(groupId)), response);
    }

}
